package com.qqtech.oss.aliyun;

import java.io.IOException;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.qqtech.core.common.exception.BizzException;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.Result;
import com.qqtech.web.context.BaseFileController;

@Controller
@RequestMapping(value = "/oss")
public class UploadController extends BaseFileController {
	private static final Logger LOG = LoggerFactory.getLogger(UploadController.class);

	@Resource
	private FileClient ossFileClient;

	/**
	 * 上传图片，并返回图片路径
	 * 
	 * @param request
	 * @return 图片路径Result.get("path")，如"/user/aaa.jpg"
	 * @throws BizzException
	 * @throws IOException
	 */
	@RequestMapping(value = "/app/upload")
	@ResponseBody
	public Result upload(HttpServletRequest request) throws BizzException, IOException {
		Result result = new Result();
		MultipartHttpServletRequest dmhRequest = (DefaultMultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = dmhRequest.getFileMap();
		if (fileMap == null || fileMap.isEmpty() || fileMap.size() == 0) {
			throw new BizzException("没有需要上传的文件");
		}
		StringBuffer sbPath = new StringBuffer();
		for (Entry<String, MultipartFile> entry : fileMap.entrySet()) {
			UploadResult ur = upload(entry.getValue(), entry.getKey());
			if (ur.isUploadOk()) {
				sbPath.append(ur.getFilePath()).append(";");
			}
		}
		String path = sbPath.toString();
		path = StringUtil.removeEndWiths(path, ";");
		result.put("path", path);
		return result;
	}

	/**
	 * 上传图片，并返回图片路径，多路径已以分号拼接好
	 * 
	 * @param request
	 * @return 图片路径Result.get("path")，如"/user/aaa.jpg;/user/bbb.png"
	 * @throws BizzException
	 * @throws IOException
	 */
	@RequestMapping(value = "/app/form")
	@ResponseBody
	public Result form(HttpServletRequest request) throws BizzException, IOException {
		Result result = new Result();
		MultipartHttpServletRequest dmhRequest = (DefaultMultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap=dmhRequest.getFileMap();
		if (fileMap == null || fileMap.isEmpty() || fileMap.size() == 0) {
			throw new BizzException("没有需要上传的文件");
		}
		fileMap = sortMapByKey(fileMap);    //按Key进行排序  
		String folder = "";
		Map<String, String[]> parameterMap = dmhRequest.getParameterMap();
		if (parameterMap != null && !parameterMap.isEmpty() && parameterMap.size() > 0) {
			for (Entry<String, String[]> entry : parameterMap.entrySet()) {
				String[] paramArr = entry.getValue();
				if (paramArr != null && paramArr.length > 0) {
					if ("folder".endsWith(entry.getKey())) {
						folder = paramArr[0];
						break;
					}
				}
			}
		}
		StringBuffer sbPath = new StringBuffer();
		for (Entry<String, MultipartFile> entry : fileMap.entrySet()) {
			UploadResult ur = upload(entry.getValue(), folder);
			if (ur.isUploadOk()) {
				sbPath.append(ur.getFilePath()).append(";");
			}
		}
		String path = sbPath.toString();
		path = StringUtil.removeEndWiths(path, ";");
		result.put("path", path);
		return result;
	}
	 /** 
     * 使用 Map按key进行排序 
     * @param map 
     * @return 
     */  
    public static Map<String, MultipartFile> sortMapByKey(Map<String, MultipartFile> map) {  
        if (map == null || map.isEmpty()) {  
            return null;  
        }  
        Map<String, MultipartFile> sortMap = new TreeMap<String, MultipartFile>(new Comparator<String>(){  
            /* 
             * int compare(Object o1, Object o2) 返回一个基本类型的整型， 
             * 返回负数表示：o1 小于o2， 
             * 返回0 表示：o1和o2相等， 
             * 返回正数表示：o1大于o2。 
             */  
            public int compare(String o1, String o2) {  
                //指定排序器按照升序排列  
                return o1.compareTo(o2);  
            }     
        });  
        sortMap.putAll(map);  
        return sortMap;  
    } 
	private UploadResult upload(MultipartFile uploadFile, String folder) throws IOException {
		String originalFilename = uploadFile.getOriginalFilename();
		originalFilename = StringUtil.removeEndWiths(originalFilename, ".do");
		String filename = ossFileClient.buildStorePath(folder, originalFilename);
		UploadResult uploadResult = ossFileClient.putObject(filename, uploadFile.getInputStream(),
				uploadFile.getSize());
		LOG.info("返回参数: uploadResult={}", uploadResult);
		return uploadResult;
	}
}
